package com.example.mall.service;

import com.example.mall.dao.CommodityInfoDao;
import com.example.mall.dao.ContainDao;
import com.example.mall.dao.OrderDao;
import com.example.mall.dto.response.SaleStatisticsResponse;
import com.example.mall.model.CommodityInfo;
import com.example.mall.model.Contain;
import com.example.mall.model.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SellService {

    @Autowired
    private CommodityInfoDao commodityInfoDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ContainDao containDao;

    public List<Order> getOrderByState(String state, Integer aID) {
        return containDao.getAll().stream().filter((item) -> isBelong(item.getcID(), aID))
                .map((item) -> orderDao.getById(item.getoID()))
                .filter((item) -> item.getStatus().equals(state))
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>((o1, o2) -> {
                    if (o1.getTimestamp().equals(o2.getTimestamp())) return 0;
                    else return -1;
                })), ArrayList::new));
    }

    public List<Order> getAllOrder(Integer aID) {
        return containDao.getAll().stream().filter((item) -> isBelong(item.getcID(), aID))
                .map((item) -> orderDao.getById(item.getoID()))
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>((o1, o2) -> {
                    if (o1.getTimestamp().equals(o2.getTimestamp())) return 0;
                    else return -1;
                })), ArrayList::new));
    }

    //判断指定商品是否属于该卖家
    public boolean isBelong(Integer cID, Integer sellerID) {
        CommodityInfo commodityInfo = commodityInfoDao.getByCSId(cID, sellerID);
        return !(commodityInfo == null);
    }

    //处理付款订单
    public boolean dealPaiedOrder(Integer oID) {
        Order order = orderDao.getById(oID);
        if (order == null)
            return false;

        List<Contain> containList = containDao.getByOid(order.getId());
        for (Contain contain : containList) {
            CommodityInfo commodityInfo = commodityInfoDao.getById(contain.getcID());
            commodityInfo.setRemain(commodityInfo.getRemain() - contain.getNum());
            commodityInfoDao.updateRemainById(commodityInfo);
        }

        order.setStatus("已完成");
        orderDao.updateStatus(order);
        return true;
    }

    //处理退款订单
    public boolean dealRufundOrder(Integer oID) {
        Order order = orderDao.getById(oID);
        if (order == null)
            return false;

        List<Contain> containList = containDao.getByOid(order.getId());
        for (Contain contain : containList) {
            CommodityInfo commodityInfo = commodityInfoDao.getById(contain.getcID());
            commodityInfo.setRemain(commodityInfo.getRemain() + contain.getNum());
            commodityInfoDao.updateRemainById(commodityInfo);
        }

        order.setStatus("已退款");
        orderDao.updateStatus(order);
        return true;
    }

    //查看指定商品销量
    public int getSale(Integer cID) {
        List<Contain> containList = containDao.getAll();
        int sale = 0;
        for (Contain contain : containList) {
            Integer tempcID = contain.getcID();
            if (tempcID.equals(cID))
                sale += contain.getNum();
        }
        return sale;
    }

    //统计一个订单的金额
    public int orderMoney(Integer oID) {
        List<Contain> containList = containDao.getByOid(oID);
        int totalPrice = 0;
        for (Contain contain : containList) {
            CommodityInfo commodityInfo = commodityInfoDao.getById(contain.getcID());
            totalPrice += commodityInfo.getPrice() * contain.getNum();
        }
        return totalPrice;
    }

    //统计一个订单的商品数量
    public int commodityNum(Integer oID) {
        List<Contain> containList = containDao.getByOid(oID);
        int totalNum = 0;
        for (Contain contain : containList) {
            CommodityInfo commodityInfo = commodityInfoDao.getById(contain.getcID());
            totalNum += contain.getNum();
        }
        return totalNum;
    }

    //查看指定日期区间的销售统计信息
    public List<SaleStatisticsResponse> getStatistics (Integer aID, Date begin, Date end) throws ParseException {
        List<SaleStatisticsResponse> saleStatisticsResponseList = new ArrayList<>();
        List<Order> orderList = getAllOrder(aID);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date current = begin;
        while (current.before(end)) {
            SaleStatisticsResponse saleStatisticsResponse = new SaleStatisticsResponse();
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            saleStatisticsResponse.setDate(fmt.format(current));
            int totalPrice = 0, totalNum = 0;

            for (Order order : orderList) {
                Date tempDate = sdf.parse(order.getTimestamp());
                if (fmt.format(tempDate).equals(fmt.format(current))) {
                    totalPrice += orderMoney(order.getId());
                    totalNum += commodityNum(order.getId());
                }
            }

            saleStatisticsResponse.setTotalMoney(totalPrice);
            saleStatisticsResponse.setOrderNum(totalNum);
            saleStatisticsResponseList.add(saleStatisticsResponse);


            Calendar calendar = Calendar.getInstance();
            calendar.setTime(current);
            calendar.add(Calendar.DATE, 1);
            current = calendar.getTime();
        }
        return saleStatisticsResponseList;
    }

}
